package cn.ilovese.collect.serviceimpl.user;

import cn.ilovese.collect.controller.socket.WebSocketServer;
import cn.ilovese.collect.datamapper.report.ReportMapper;
import cn.ilovese.collect.datamapper.report.ScoreMapper;
import cn.ilovese.collect.datamapper.user.UserMapper;
import cn.ilovese.collect.datamapper.workermessage.WorkerMessageMapper;
import cn.ilovese.collect.po.report.Score;
import cn.ilovese.collect.po.workermessage.WorkerMessage;
import cn.ilovese.collect.service.user.MessageService;
import cn.ilovese.collect.util.Constant;
import cn.ilovese.collect.vo.NullVO;
import cn.ilovese.collect.vo.ResultVO;
import cn.ilovese.collect.vo.workermessage.WorkerMessageVO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@CacheConfig(cacheNames = "message",cacheManager = "cacheManager")
public class MessageServiceImpl implements MessageService {
    @Resource
    WorkerMessageMapper workerMessageMapper;

    @Resource
    ScoreMapper scoreMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public int getMessageNums(Integer uid) {
        return workerMessageMapper.countStatus(0,uid);
    }

    @Override
    public ResultVO<List<WorkerMessageVO>> getMyMessage(Integer uid) {
        List<WorkerMessage> messageList=workerMessageMapper.selectByToUserId(uid);
        if(messageList==null)
            return new ResultVO<>(Constant.REQUEST_FAIL,"获取消息列表失败",new ArrayList<>());
        List<WorkerMessageVO> res=new ArrayList<>();
        for(WorkerMessage workerMessage:messageList){
            WorkerMessageVO workerMessageVO=new WorkerMessageVO(workerMessage);
            workerMessageVO.setUserName(userMapper.selectByPrimaryKey(workerMessageVO.getFromUserId()).getUsername());
            Score temp=scoreMapper.selectByWorkerAndReport(workerMessage.getReportId(),workerMessage.getFromUserId());
            if(workerMessageVO.getMessageType()==0&&temp!=null) {
                workerMessageVO.setScoreContent(temp.getDescription());
                workerMessageVO.setScore(temp.getScore());
            }
            res.add(workerMessageVO);
        }
        Collections.reverse(res);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"查询消息列表成功",res);
    }

    @Override
    public ResultVO<String> setRead(Integer messageId,Integer uid) {
        WorkerMessage workerMessage=workerMessageMapper.selectByPrimaryKey(messageId);
        workerMessage.setStatus(1);
        workerMessageMapper.updateByPrimaryKey(workerMessage);
        WebSocketServer.sendMessageToSpecificUser(workerMessageMapper.countStatus(0,uid),uid);
        return new ResultVO<>(Constant.REQUEST_SUCCESS,"设置已读成功","OK");
    }
}
